package com.wzw.springboot.principle.mvc.handler;

import com.wzw.springboot.principle.use.json.JacksonHandler;
import org.springframework.util.Assert;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * @author Wangzhiwen
 */
public class ServletHandler {

    private ServletHandler() {

    }

    private static void setResponse(HttpServletResponse response) {
        response.setContentType("application/json; charset=UTF-8");
        response.setCharacterEncoding(StandardCharsets.UTF_8.displayName());
    }

    private static String toString(Object obj) {
        return JacksonHandler.toJsonString(obj);
    }

    public static void write(HttpServletResponse response, Object obj) throws IOException {
        setResponse(response);
        response.getWriter().write(toString(obj));
    }

    public static HttpServletRequest getServletRequest() {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        Assert.notNull(requestAttributes, "ServletRequestAttributes Is Null");
        return requestAttributes.getRequest();
    }
}
